import isFunctionComponent from './isFunctionComponent';
import mountNativeElement from './mountNativeElement';
import isFunction from './isFunction';
export default function mountComponent(virtualDOM, container, oldDOM) {
  let nextVirtualDOM = null;
  let component = null;
  // 判断组件是类组件还是函数组件
  if (isFunctionComponent(virtualDOM)) {
    // 函数组件
    nextVirtualDOM = buildFunctionComponent(virtualDOM);
  } else {
    // 类组件
    nextVirtualDOM = buildClassComponent(virtualDOM);
    component = nextVirtualDOM.component;
  }
  if (isFunction(nextVirtualDOM)) {
    // 我们渲染的组件返回的是另外一个组件，也就是 nextVirtualDOM 是组件
    // oldDOM，用于组件对比时不是同一个组件时删除旧的 DOM
    mountComponent(nextVirtualDOM, container, oldDOM);
  } else {
    // nextVirtualDOM 是 Native Element
    // oldDOM，用于组件对比时不是同一个组件时删除旧的 DOM
    mountNativeElement(nextVirtualDOM, container, oldDOM);
  }
  if (component) {
    component.componentDidMount();
    if (component.props && component.props.ref) {
      component.props.ref(component);
    }
  }
}

function buildFunctionComponent(virtualDOM) {
  // 调用函数组件函数时传递 props
  return virtualDOM.type(virtualDOM.props || {});
}

function buildClassComponent(virtualDOM) {
  // 实例化类组件时传递 props
  const component = new virtualDOM.type(virtualDOM.props || {});
  const nextVirtualDOM = component.render();
  // 将组件实例对象 component 挂载到 nextVirtualDOM 上
  nextVirtualDOM.component = component;
  return nextVirtualDOM;
}
